package com.ruoyi.system.mobile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;

import com.ruoyi.common.exception.BaseException;
import com.ruoyi.system.basicInformation.domain.TWfActivityInstance;
import com.ruoyi.system.basicInformation.service.ITWfActivityInstanceService;
import com.ruoyi.system.basicInformation.vo.TWfActivityInstanceVo;
import com.ruoyi.system.frontierEvent.bo.TAttachAddBo;
import com.ruoyi.system.frontierEvent.service.ITAttachService;
import com.ruoyi.system.mobile.bo.TEventAddBo;
import com.ruoyi.system.mobile.bo.TEventEditBo;
import com.ruoyi.system.mobile.bo.TEventQueryBo;
import com.ruoyi.system.mobile.domain.Event;
import com.ruoyi.system.mobile.mapper.ActivityInstanceMapper;
import com.ruoyi.system.mobile.mapper.EventMapper;
import com.ruoyi.system.mobile.service.EventService;
import com.ruoyi.system.mobile.vo.EventVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 案件信息Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-19
 */
@Service
public class EventServiceImpl extends ServiceImpl<EventMapper, Event> implements EventService {
    @Autowired
    private  ITAttachService iTAttachService;


    private ActivityInstanceMapper activityInstanceMapper;
    @Autowired

    private ITWfActivityInstanceService itWfActivityInstanceService;
    @Override
    public EventVo queryById(Long id){
        Event db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, EventVo.class);
    }

    @Override
    public List<EventVo> queryList(TEventQueryBo bo) {
        LambdaQueryWrapper<Event> lqw = Wrappers.lambdaQuery();
        List<EventVo> eventVos=new ArrayList<>();
        if(bo.getReportUserId()!=null&&bo.getReportUserId()>0){
            lqw.eq(bo.getReportUserId()>0, Event::getReporterObjectId, bo.getReportUserId());
            lqw.eq(StrUtil.isNotBlank(bo.getEvtState()), Event::getEvtState, bo.getEvtState());
            eventVos = entity2Vo(this.list(lqw));
            //根据案件Id查询附件列表
            if(bo.getReportUserId()!=null&&bo.getReportUserId()>0) {
                for (int i = 0; i < eventVos.size(); i++) {
                    //查询环节列表
                    List<TWfActivityInstanceVo> tWfActivityInstanceVos = itWfActivityInstanceService.caseQueryById(eventVos.get(i).getId());
                    eventVos.get(i).setActivityInstanceVoList(tWfActivityInstanceVos);
                    for (int j = 0; j <tWfActivityInstanceVos.size(); j++) {
                        //查询附件列表
                        eventVos.get(i).setAttachIds(iTAttachService.queryCaseAttachList(eventVos.get(i).getId(),tWfActivityInstanceVos.get(j).getId()));
                    }
                }
            }
        }else if(bo.getOperatorUserId()>0||bo.getReceiveUserId()>0){
            eventVos=baseMapper.querypPatrolList(bo.getOperatorUserId(),bo.getReceiveUserId(),bo.getEvtState());
            //根据案件Id查询附件列表
            if(bo.getReportUserId()!=null&&bo.getReportUserId()>0) {
                for (int i = 0; i < eventVos.size(); i++) {
                    //查询环节列表
                    List<TWfActivityInstanceVo> tWfActivityInstanceVos = itWfActivityInstanceService.caseQueryById(eventVos.get(i).getId());
                    eventVos.get(i).setActivityInstanceVoList(tWfActivityInstanceVos);
                    for (int j = 0; j <tWfActivityInstanceVos.size(); j++) {
                        //查询附件列表
                        eventVos.get(i).setAttachIds(iTAttachService.queryCaseAttachList(eventVos.get(i).getId(),tWfActivityInstanceVos.get(j).getId()));
                    }
                }
            }
        }

        return eventVos;
    }

    /**
     * 处置人查询案件列表
     */
    @Override
    public List<EventVo> querypPatrolList(TEventQueryBo bo) {
        return this.baseMapper.querypPatrolList(bo.getOperatorUserId(),bo.getReceiveUserId(),bo.getEvtState());
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<EventVo> entity2Vo(Collection<Event> collection) {
        List<EventVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, EventVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Event> page = (Page<Event>)collection;
            Page<EventVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(TEventAddBo bo) {
        bo.setEvtState("1");
        boolean save =false;
        try{
            Event add = BeanUtil.toBean(bo, Event.class);
            validEntityBeforeSave(add);
            //新增案件
            this.save(add);
            TWfActivityInstance activityInstance=new TWfActivityInstance();
            activityInstance.setEvtId(add.getId());
            activityInstance.setEvtState(new Long(1));
            //新增案件流程
            itWfActivityInstanceService.save(activityInstance);
            if(add.getId()!=0&&activityInstance.getId()!=0&&bo.getAttachIds().size()>0){
                //新增附件记录
                for (int i = 0; i <bo.getAttachIds().size() ; i++) {
                    TAttachAddBo tAttachAddBo = new TAttachAddBo();
                    tAttachAddBo.setEvtId(add.getId());
                    tAttachAddBo.setEvtActType(new Long(1));
                    tAttachAddBo.setFileId(bo.getAttachIds().get(i));
                    tAttachAddBo.setFileName(bo.getFileNameList().get(i));
                    tAttachAddBo.setEvtWfId(activityInstance.getId());
                    save=iTAttachService.insertByAddBo(tAttachAddBo);
                }
            }else{
                throw new BaseException("案件上报失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new BaseException("案件上报失败");
        }
        return save;
    }

    @Override
    public Boolean updateByEditBo(TEventEditBo bo) {
        Event update = BeanUtil.toBean(bo, Event.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Event entity){
        //TODO 做一些数据校验,如唯一约束
    }


}
